package com.zpz.framework.zpzoauth.common.encrypt;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author zhangpanzhi
 * @description AES加解密算法、通讯签名
 * @date 2018/5/30 14:38
 **/

public class AESUtil {
    // PKCS7Padding 参考https://my.oschina.net/nicsun/blog/95632
    private static final String ALGORITHM_STR = "AES/CBC/PKCS5Padding";//"算法/模式/补码方式"
    private static final String ALGORITHM = "AES";//算法
    private static final String CODE="UTF-8";
    /*
     * 加密
     * */
    public static byte[] encrypt(byte[] content, String secretKey) throws Exception {
        byte[] raw = Base64.decodeBase64(secretKey.getBytes(CODE));
        SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);//实例化一个用AES加密算法的密钥生成器
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);// 创建密码器
        IvParameterSpec iv = new IvParameterSpec(raw);//使用CBC模式，需要一个向量iv，可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);// 初始化密码器
        byte[] encrypted = cipher.doFinal(content);
        return encrypted;
    }

    public static byte[] decrypt(byte[] content, String secretKey) throws Exception {
        byte[] raw = Base64.decodeBase64(secretKey.getBytes(CODE));
        SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
        IvParameterSpec iv = new IvParameterSpec(raw);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec,iv);
        byte[] original = cipher.doFinal(content);
        return original;
    }

}
